#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include "log.hpp"
#include "addr.hpp"
using namespace std;
const string sep = ": ";
string pathname = "./dict.txt";
class dict
{
public:
    dict(const string p = pathname) : _pathname(p) {}
    bool loaddict()
    {
        ifstream in(_pathname);
        if (!in.is_open())
        {
            use_log(loglevel::DEBUG) << "打开字典: " << _pathname << " 错误";
            return false;
        }
        string line;

        while (getline(in, line))
        {
            int pos = line.find(sep);
            if(pos==string::npos) { 
                use_log(loglevel::DEBUG) << "当前加载错误，继续向下加载";
                  continue;
            } 
            string word = line.substr(0, pos);
            string chinese = line.substr(pos + 2,string::npos);
            if (word.size() == 0 || chinese.size() == 0)
            {
                use_log(loglevel::DEBUG) << "加载错误";
                continue;
            }

            _dict.insert({word, chinese});
            use_log(loglevel::DEBUG) << "成功加载："<<line;;
        }
        in.close();
        return true;
    }
    string translate(const string src,  inetaddr client)//const类型对象只能调用非const修饰的成员函数等
    {
        if (!_dict.count(src))
        {
            use_log(loglevel::DEBUG) << "有用户进入到了翻译模块, client: [" << client.ip() << " : " << client.port() << "]# 查询 " << src << "->None";
            return "None";
        }
        auto iter = _dict.find(src);
        use_log(loglevel::DEBUG) << "有用户进入到了翻译模块, client: [" << client.ip() << " : " << client.port() << "]# 查询 " << src << "->" << iter->second;
        return iter->second;
    }

    ~dict() {}

private:
    string _pathname;
    unordered_map<string, string> _dict;
};